package com.briup.bookstore.service.impl;

import com.briup.bookstore.dto.OrderCreateDTO;
import com.briup.bookstore.dto.OrderDeliveryDTO;
import com.briup.bookstore.dto.OrderPaySuccessDTO;
import com.briup.bookstore.dto.OrderSearchDTO;
import com.briup.bookstore.exception.BookStoreException;
import com.briup.bookstore.mapper.BookMapper;
import com.briup.bookstore.mapper.OrderItemMapper;
import com.briup.bookstore.mapper.OrderMapper;
import com.briup.bookstore.mapper.ShopcarMapper;
import com.briup.bookstore.po.Order;
import com.briup.bookstore.po.OrderItem;
import com.briup.bookstore.po.Shopcar;
import com.briup.bookstore.po.ext.OrderExtend;
import com.briup.bookstore.service.OrderService;
import com.briup.bookstore.utils.BeanCopyUtils;
import com.briup.bookstore.vo.OrderBookVO;
import com.briup.bookstore.vo.OrderDetailVO;
import com.briup.bookstore.vo.OrderInfoVO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * @author qinyc
 * @description 针对表【es_order】的数据库操作Service实现
 * @createDate 2023-07-18 21:33:14
 */
@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderItemMapper orderItemMapper;

    @Autowired
    private ShopcarMapper shopcarMapper;

    @Autowired
    private BookMapper bookMapper;

    @Override
    public PageInfo<OrderInfoVO> getPageOrder(Integer pageNum, Integer pageSize, OrderSearchDTO orderSearchDTO) {
        // 查询数据
        List<OrderExtend> list = orderMapper.selectOrdersByCondition(orderSearchDTO);
        list.forEach(i -> i.genPrice());
        PageHelper.startPage(pageNum, pageSize);
        List<OrderInfoVO> vos = BeanCopyUtils.copyBeanList(list, OrderInfoVO.class);
        return PageInfo.of(vos);
    }

    @Override
    public OrderDetailVO getOrderById(String orderId) {
        OrderExtend orderExtend = orderMapper.selectOrderDetailById(orderId);
        orderExtend.genPrice();
        OrderDetailVO vo = BeanCopyUtils.copyBean(orderExtend, OrderDetailVO.class);
        vo.setOrderItems(BeanCopyUtils.copyBeanList(orderExtend.getOrderItems(), OrderBookVO.class));
        return vo;
    }

    @Override
    public void closeOrder(String id) {
        // 判断当前订单状态是否是已下单未支付
        Order order = orderMapper.selectOrderById(id);
        if (order.getStatus() != 1) {
            throw new BookStoreException(BookStoreException.CodeMsgEnum.ORDER_CAN_NOT_CLOSE);
        }
        // 关闭该订单
        orderMapper.updateStatusToClose(id);
        List<OrderItem> list = orderItemMapper.findByOrderId(id);
        for (OrderItem item : list) {
            bookMapper.updateStoreNumById(item.getNum(),item.getBookId());

        }

    }

    @Override
    public void delivery(OrderDeliveryDTO orderDeliveryDTO) {
        // 判断参数是否为空
        if (orderDeliveryDTO.getDistributionMode() == null) {
            throw new BookStoreException(BookStoreException.CodeMsgEnum.DISTRIBUTION_MODE_IS_NULL);
        }
        if (orderDeliveryDTO.getTrackingNumber() == null) {
            throw new BookStoreException(BookStoreException.CodeMsgEnum.TRACKING_NUMBER_IS_NULL);
        }
        // 判断当前订单状态是否是已支付未发货
        Order order = orderMapper.selectOrderById(orderDeliveryDTO.getOrderId());
        if (order.getStatus() != 2) {
            throw new BookStoreException(BookStoreException.CodeMsgEnum.ORDER_CAN_NOT_DELIVERY);
        }
        // 发货
        orderMapper.updateStatusToDelivery(orderDeliveryDTO);
    }

    @Override
    @Transactional
    public OrderDetailVO createOrder(OrderCreateDTO orderCreateDTO, int userId) {
        Order order = BeanCopyUtils.copyBean(orderCreateDTO, Order.class);
        order.setUserId(userId);
        if (!StringUtils.hasText(orderCreateDTO.getReceiveAddress()) || !StringUtils.hasText(orderCreateDTO.getReceivePhone()) || !StringUtils.hasText(orderCreateDTO.getReceiveUsername()))
            throw new BookStoreException(BookStoreException.CodeMsgEnum.ADDRESS_CAN_NOT_NULL);
        orderMapper.save(order);
        orderCreateDTO.getShopCarIds().forEach(i->{
            Shopcar shopcar = shopcarMapper.findById(i);
            OrderItem item = BeanCopyUtils.copyBean(shopcar, OrderItem.class);
            item.setOrderId(order.getId());
            orderItemMapper.save(item);
            shopcarMapper.deleteById(i);
            bookMapper.updateStoreNumById(Math.negateExact(item.getNum()),item.getBookId());
        });

        OrderDetailVO vo = getOrderById(order.getId());
        return  vo;

    }

    @Override
    public void completeOrder(String orderId) {
        Order order = orderMapper.selectOrderById(orderId);
        if (order.getStatus() != 3) {
            throw new BookStoreException(BookStoreException.CodeMsgEnum.ORDER_CAN_NOT_COMPLETE);

        }
        orderMapper.completeOrder(orderId);
    }

    @Override
    public List<OrderInfoVO> getOrders(int userId,OrderSearchDTO orderSearchDTO) {
        List<OrderExtend> list = orderMapper.selectOrderDetailByUserId(userId,orderSearchDTO);
        list.forEach(OrderExtend::genPrice);
        list.forEach(i -> log.debug(i.toString()));

        List<OrderInfoVO> vos = BeanCopyUtils.copyBeanList(list, OrderInfoVO.class);
        return vos;
    }

    @Override
    public void paySuccess(OrderPaySuccessDTO paySuccessDTO) {
        orderMapper.paySuccess(paySuccessDTO);
    }
}




